﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using TransControlSystem.Dao;
using TransControlSystem.Model;
using TransControlSystem.Utils;
using TransControlSystem.ViewModel.Common.Command;

namespace TransControlSystem.ViewModel.Common
{
    public class UserManagementViewModel : ViewModelBase
    {
        /// <summary>
        /// 删除回调信息
        /// </summary>
        private string RemoveCallbackMessage;
        /// <summary>
        /// 要删除的用户
        /// </summary>
        private User RemoveUser;
        /// <summary>
        /// Open the create user form command 打开创建用户窗体命令
        /// </summary>
        public DelegateCommand OpenTheCreateUserFormCommand { get; set; }

        /// <summary>
        /// Open the edit user form command 打开编辑用户窗体命令
        /// </summary>
        public DelegateCommand OpenTheEditUseFormCommand { get; set; }

        /// <summary>
        /// Delete user command 删除用户命令
        /// </summary>
        public DelegateCommand RemoveUserCommand { get; set; }

        /// <summary>
        /// Hide user management form 隐藏用户管理窗体
        /// </summary>
        public DelegateCommand HideUserManagementWindowCommand { get; set; }

        /// <summary>
        /// search 搜索命令
        /// </summary>
        public DelegateCommand SearchCommand { get; set; }

        /// <summary>
        /// User list of account authority management 账户权限管理用户列表
        /// </summary>
        private ObservableCollection<User> _UserQueue = new ObservableCollection<User>();
        /// <summary>
        /// User list of account authority management 账户权限管理用户列表
        /// </summary>
        public ObservableCollection<User> UserQueue
        {
            get
            {
                return _UserQueue;
            }
            set
            {
                _UserQueue = value;
                RaisePropertyChanged("UserQueue");
            }
        }
        /// <summary>
        /// 搜索用户名
        /// </summary>
        private string _UserName;
        /// <summary>
        /// 搜索用户名
        /// </summary>
        public string UserName
        {
            get
            {
                return _UserName;
            }
            set
            {
                _UserName = value;
                RaisePropertyChanged("UserName");
            }
        }

        /// <summary>
        /// LoadUserList 加载权限列表
        /// </summary>
        private void LoadUserList()
        {
            string WhereStr = "";
            if (UserName != null && UserName.Trim().Length > 0)
            {
                if (XyhUtils.IsHasSQLInject(UserName))
                {
                    WindowManager.ShowWarning("警告", "用户名不可使用包含SQL注入关键词的内容进行搜索操作！");
                    return;
                }
                WhereStr = " where UserName LIKE '%" + UserName.Trim() + "%'";
            }
            string sql = "select * from [User] " + WhereStr + " order by Id;";
            Application.Current.Dispatcher.Invoke((Action)delegate ()
            {
                UserQueue = DapperTools.QueryOc<User>(sql);
                foreach (User user in UserQueue)
                {
                    user.Password = XyhUtils.Decrypt(user.Password);
                }
            });
        }

        /// <summary>
        /// Constructors
        /// </summary>
        public UserManagementViewModel()
        {
            RemoveCallbackMessage = "confirm deletion";
            LoadUserList();

            //使用委托初始化搜索命令
            SearchCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SearchHandler)
            };
            //使用委托初始化打开创建用户窗体命令
            OpenTheCreateUserFormCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(OpenTheCreateUserWindowHandler)
            };
            //使用委托初始化隐藏创建用户窗体命令
            HideUserManagementWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(HideUserManagementWindowHandler)
            };
            //使用委托初始化打开编辑用户命令
            OpenTheEditUseFormCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(OpenTheEditUseFormHandler)
            };
            //使用委托初始化删除命令
            RemoveUserCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(RemoveUserHandler)
            };
            //注册消息 用于刷新用户列表
            Messenger.Default.Register<NotificationMessage>(this, (nm) =>
            {
                if (nm.Notification == "ReLoadUserQueue")
                {
                    LoadUserList();
                }
            });
            //注册消息 用于删除用户用户
            Messenger.Default.Register<NotificationMessage>(this, (nm) =>
            {
                if (nm.Notification == RemoveCallbackMessage)
                {
                    RemoveUserFun();
                }
            });
        }
        /// <summary>
        /// 搜索处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void SearchHandler(object obj)
        {
            LoadUserList();
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        private void RemoveUserFun()
        {
            string RemoveUserSql = @"DELETE [User] where Id = @Id";
            int result = DapperTools.Delete<User>(RemoveUserSql, RemoveUser);
            if (result > 0)
            {
                LoadUserList();
                WindowManager.ShowWarning("提示", "尊敬的用户，您删除操作成功。");
            }
        }

        /// <summary>
        /// 打开创建用户窗体处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void OpenTheCreateUserWindowHandler(object obj)
        {
            WindowManager.Show("CreateUserWindow", null);
        }

        /// <summary>
        /// 打开编辑用户窗体处理程序
        /// </summary>
        /// <param name="obj">参数：传递用户表User主键字段Id的值</param>
        private void OpenTheEditUseFormHandler(object obj)
        {
            User UserInfo = new User();
            UserInfo.Id = int.Parse(obj.ToString());
            WindowManager.ShowEdit("EditUserWindow", UserInfo);
        }
        /// <summary>
        /// 删除用户处理程序
        /// </summary>
        /// <param name="obj">参数：被删除用户的主键Id</param>
        /// <returns></returns>
        private void RemoveUserHandler(object obj)
        {
            try
            {
                RemoveUser = new User();
                RemoveUser.Id = int.Parse(obj.ToString());
                string GetUserSql = @" select * from [User] where Id = @Id";
                RemoveUser = DapperTools.Query<User>(GetUserSql, RemoveUser);
                if (RemoveUser.UserName == "管理员")
                {
                    WindowManager.ShowWarning("提示", "尊敬的用户，您无法删除系统默认管理员。");
                    return;
                }
                else
                {
                    WindowManager.ConfirmShow("删除提示", "您确认要删除用户名为【" + RemoveUser.UserName + "】的用户信息吗？", RemoveCallbackMessage);
                }
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "删除用户异常");
            }

        }

        /// <summary>
        /// 隐藏本窗体处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void HideUserManagementWindowHandler(object obj)
        {
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideUserManagementWindow"));
        }
    }
}
